// index.js
// 获取应用实例
const app = getApp()
Page({
  data: {
    text: '欢迎使用觅晴天气！',
    marqueePace: 0.8,//滚动速度
    marqueeDistance: 0,//初始滚动距离
    marqueeDistance2: 0,
    marquee2copy_status: false,
    marquee2_margin: 60,
    size: 14,
    orientation: 'left',//滚动方向
    interval: 20, // 时间间隔,
    city: '',
    days: ['今天', '明天', '后天'],
    locationX: '',
    locationY: '',
    id: '',
    nonet: true,
    show:false
  },
  onLoad: function (option) {
    var that = this
    wx.onNetworkStatusChange(function (res) {
      console.log('111--', res)
      if (res.networkType == "none") {
        wx.showToast({
          title: '网络不可用!',
          icon: 'error',
          duration: 2000
        })
        that.setData({
          nonet: false,
          show:true
        })
      } else {
        that.setData({
          nonet: true,
          show:false
        })
      }
    })
    if (option.lat && option.lon) {
      this.getCityByLocation(option.lat, option.lon)
    } else {
      this.getLocationXY()
    }
    function zero (str) {
      return str<10 ? '0'+str :str
    }
    var date = new Date();
    var huor = date.getHours().toString()
    var minutes = date.getMinutes().toString()
    var updatetime = zero(huor) + ':' + zero(minutes)
    this.setData({
      updatetime: updatetime
    })
  },
  //获得当前的坐标，通过百度地图API
  //
  getLocationXY: function () {
    var that = this;
    wx.getLocation({
      success: function (res) {
        var locationX = res.latitude;
        var locationY = res.longitude;
        //通过坐标获得具体的位置
        that.getCityByLocation(locationX, locationY);
        // console.log(res)
        if (!res) {
          console.log(11)
        }
      },
      fail: function () {
        wx.hideLoading();
        wx.getSetting({
          success: function (res) {
            if (!res.authSetting['scope.userLocation']) {
              wx.showModal({
                title: '',
                content: '请允许觅晴天气获取您的定位',
                confirmText: '授权',
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting({
                      withSubscriptions: true,
                    })
                  } else {
                    console.log('get location fail');
                  }
                }
              })
            } else {
              //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
              that.showModal({
                title: '',
                content: '请在系统设置中打开定位服务',
                confirmText: '确定',
                success: function (res) {}
              })
            }
          }
        })
      }
    })
  },
  //通过坐标获得具体的位置名称,关联腾讯地图API
  getCityByLocation: function (locationX, locationY) {
    var that = this;

    wx.request({
      url: 'https://geoapi.qweather.com/v2/city/lookup',
      data: {
        location: locationY + "," + locationX,
        key: '7364f1d6588041229b5a69633d058c95',
      },
      success: function (res) {
        if (res.data.code == 400 || res.data.code == 401 || res.data.code == 402 || res.data.code == 403 || res.data.code == 404) {
          wx.showToast({
            title: '获取生活指数信息失败',
            icon: 'error',
            duration: 2000
          })
        }
        // console.log(res)
        var city = res.data.location[0].adm2;
        var cityIds = res.data.location[0].id;
        that.setData({
          city: city,
          id: cityIds
        });
        // free-api接口
        wx.request({
          url: 'https://aider.meizu.com/app/weather/listWeather',
          data: {
            cityIds: '101230708'
          },
          success: function (res) {
            // console.log(res)
            if (res.data.code == 400 || res.data.code == 401 || res.data.code == 402 || res.data.code == 403 || res.data.code == 404) {
              wx.showToast({
                title: '获取信息失败',
                icon: 'error',
                duration: 2000
              })
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '获取生活指数信息失败',
              icon: 'error',
              duration: 2000
            })
          },
          complete: function (res) {},

        });
      },
      fail: function (res) {
        wx.showToast({
          title: '获取生活指数信息失败',
          icon: 'erro',
          duration: 2000
        })
      },
      complete: function (res) {},

    });
    var that = this;
    //和风api 获取天气
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/now',
      data: {
        location: locationY + "," + locationX,
        key: 'c82edbacf76d4f0e8921b0fd3ffe7410',
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code == 400 || res.data.code == 401 || res.data.code == 402 || res.data.code == 403 || res.data.code == 404) {
          wx.showToast({
            title: '获取生活指数信息失败',
            icon: 'erro',
            duration: 2000
          })
        }
        var now = res.data.now
        now['updateTime'] = res.data.updateTime
        that.setData({
          info: {
            weather: now
          }
        })

        // }else if(now.text=='阴'){
        //   document.getElementById('backgorund').className='cloudy'
        // }else if(now.text=='小雨'||now.text=='大雨'||now.text=='雷阵雨'){
        //   document.getElementById('backgorund').className='rain'
        // }
      },
      fail: function (res) {
        wx.showToast({
          title: '获取生活指数信息失败',
          icon: 'erro',
          duration: 2000
        })
      },

    })
    //和风天三天气天信息
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/3d',
      data: {
        location: locationY + "," + locationX,
        key: 'c82edbacf76d4f0e8921b0fd3ffe7410',
      },
      success: function (res) {
        // console.log(res.data)
        if (res.data.code == 400 || res.data.code == 401 || res.data.code == 402 || res.data.code == 403 || res.data.code == 404) {
          wx.showToast({
            title: '获取生活指数信息失败',
            icon: 'error',
            duration: 2000
          })
        }
        var future = res.data.daily
        that.setData({
          future: future
        })

        // console.log('----',that.data.future);
      },
      fail: function (res) {
        wx.showToast({
          title: '获取生活指数信息失败',
          icon: 'error',
          duration: 2000
        })
      },

    })
    //获取生活指数
    wx.request({
      url: 'https://devapi.qweather.com/v7/indices/1d',
      data: {
        location: locationY + "," + locationX,
        type: "3,1",
        key: 'c82edbacf76d4f0e8921b0fd3ffe7410',
      },
      success: function (res) {
        // console.log('------',res)
        if (res.data.code == 400 || res.data.code == 401 || res.data.code == 402 || res.data.code == 403 || res.data.code == 404) {
          wx.showToast({
            title: '获取信息失败',
            icon: 'error',
            duration: 2000
          })
        }
        var liveO = res.data.daily[0]
        var liveT = res.data.daily[1]
        that.setData({
          liveO: liveO,
          liveT: liveT
        });
        // console.log('指数',that.data.liveT);
      },
      fail: function (res) {
        wx.showToast({
          title: '获取生活指数信息失败',
          icon: 'erro',
          duration: 2000
        })
      },
      complete: function (res) {},

    });
    //free-api获取接口

  },

  onShow: function () {
    var vm = this;
 
    var length = vm.data.text.length * vm.data.size;//文字长度
 
    var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
 
    vm.setData({
 
      length: length,
 
      windowWidth: windowWidth,
 
      marquee2_margin: length < windowWidth ? windowWidth - length : vm.data.marquee2_margin//当文字长度小于屏幕长度时，需要增加补白
 
    });
 
    vm.run1();// 水平一行字滚动完了再按照原来的方向滚动
 
 
  },
 
  run1: function () {
 
    var vm = this;
 
    var interval = setInterval(function () {
 
      if (-vm.data.marqueeDistance < vm.data.length) {
        vm.setData({
          marqueeDistance: vm.data.marqueeDistance - vm.data.marqueePace,
        });
      } else {
        clearInterval(interval);
        vm.setData({
          marqueeDistance: vm.data.windowWidth
        });
        vm.run1();
      }
    }, vm.data.interval);
  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onPullDownRefresh: function () {
    //     wx.showNavigationBarLoading() //在标题栏中显示加载

    // //模拟加载

    // setTimeout(function()

    // {
    // // complete
    // wx.showLoading({
    //     title: '刷新',
    //   })
    // wx.hideNavigationBarLoading() //完成停止加载

    // wx.stopPullDownRefresh() //停止下拉刷新

    // },1500);
    var that = this
    wx.showNavigationBarLoading();
    wx.e
    wx.showLoading({
      title: '刷新',
    })
    setTimeout(function ()

      {
        // complete
        wx.showLoading({
          title: '刷新',
        })
        wx.hideNavigationBarLoading() //完成停止加载

        wx.stopPullDownRefresh() //停止下拉刷新
        wx.hideLoading({
          success: (res) => {
            if (res.errMsg == 'hideLoading:ok') {

              wx.redirectTo({
                url: '/pages/index/index',
                success: function (res) {
                  console.log(res.errMsg)
                  if (res.errMsg) {
                    wx.showToast({
                      title: '刷新成功',
                      icon: 'success',
                      duration: 2000
                    })
                    wx.hideLoading()
                  }
                },
                fail: (res) => {
                  if (res) {
                    wx.showToast({
                      title: '刷新失败',
                      icon: 'error',
                      duration: 2000
                    })
                    that.onLoad()
                  }
                },
                complete: (res) => {},
              })
            }
          },
        })
      }, 1500);


  },

  onReachBottom: function () {
    wx.showToast({
      title: '没有内容咯！',
      icon: 'none',
      duration: 2000
    })
  },

  onShareAppMessage: function () {
    title: "天气预报小程序你值得拥有"
  },

})